import 'dart:io';

import 'package:cloud_phone_manager/provider/AdbCurrentChangeProvider.dart';
import 'package:cloud_phone_manager/provider/AdbDevicesProvider.dart';
import 'package:cloud_phone_manager/utils/CmdUtils.dart';
import 'package:cloud_phone_manager/utils/ConnectUtils.dart';
import 'package:cloud_phone_manager/utils/FileUtils.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

/// 设备列表
class DevicesInfoView extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _DevicesListInfoView();
}

class _DevicesListInfoView extends State<DevicesInfoView> {
  final List<DeviceHardAndSoftInfo> _list = [];
  final List<DeviceHardAndSoftInfo> _displayInfoList = [];
  final List<DeviceHardAndSoftInfo> _otherInfoList = [];
  AdbCurrentChangeProvider? provider;
  bool _mounted = false;
  bool _isInit = false;
  File _cover = File("");

  @override
  void initState() {
    super.initState();
    _mounted = true;
    if (!_isInit) {
      _isInit = true;
      init();
    }
  }

  void init(){
    _list.clear();
    _displayInfoList.clear();
    _otherInfoList.clear();
    CmdUtils.screenshotAdbToPhone("screen.png",
            (success, error, process, successListener) {
          debugPrint("截取成功");
          FileUtils.getDeviceCoverPath().then((value) => {
            debugPrint("拉取成功"),
            CmdUtils.pullFileToComputer(
                "/sdcard/screen.png",
                " ${value}\\screen.png",
                    (success, error, process, successListener) {}),
            setState(() {
              _cover = File("${value}\\screen.png");
              //debugPrint(_cover.path);
            })
          });
        });
    initBaseInfo();
    initDisplayInfo();
  }

  ///更新屏幕信息
  void initDisplayInfo(){
    CmdUtils.displaySize((success, error, process, successListener) {
      debugPrint("屏幕信息"+success);
      List<String> array = success.split("\r\n");
      String bufferA = "";
      String bufferB = "";
      for(String item in array){
        if(!item.contains(":")){
          continue;
        }
        item = item.replaceAll("：", ":");
        String name = item.trim().split(":")[1].trim();
        String key = item.trim().split(":")[0].trim();
        if(key.startsWith("Physical")){
          name = "【物理分辨率】$name";
          bufferA = "$bufferA $name";
        }else if(key.startsWith("Override")){
          name = "【重置分辨率】$name";
          bufferB = "$bufferB $name";
        }
      }
      //debugPrint(buffer);
      setState(() {
        if(!_mounted){
          return;
        }
        if(bufferA.isNotEmpty){
          _displayInfoList.add(DeviceHardAndSoftInfo("物理尺寸", bufferA));//0
        }
        if(bufferB.isNotEmpty){
          _displayInfoList.add(DeviceHardAndSoftInfo("重置尺寸", bufferB));//0
        }

      });
    });
    CmdUtils.displayDensity((success, error, process, successListener) {
      //debugPrint(success);
      List<String> array = success.split("\r\n");
      String buffer = "";
      for(String item in array){
        if(!item.contains(":")){
          continue;
        }
        item = item.replaceAll("：", ":");
        String name = item.trim().split(":")[1].trim();
        String key = item.trim().split(":")[0].trim();
        if(key.startsWith("Physical")){
          name = "【物理密度】$name";
          buffer = "$buffer $name";
        }else if(key.startsWith("Override")){
          name = "【重置密度】$name";
          buffer = "$buffer $name";
        }
      }
      //debugPrint(buffer);
      setState(() {
        if(!_mounted){
          return;
        }
        _displayInfoList[1].name = buffer;
      });
    });
  }

  /// 基础信息
  void initBaseInfo(){
    _list.add(DeviceHardAndSoftInfo("型号", "_"));//0
    _list.add(DeviceHardAndSoftInfo("安卓系统版本", "_"));//1
    _list.add(DeviceHardAndSoftInfo("安卓SDK版本", "_"));//2
    _list.add(DeviceHardAndSoftInfo("CPU架构", "_"));//3
    _list.add(DeviceHardAndSoftInfo("电池温度", "_"));//4
    _list.add(DeviceHardAndSoftInfo("电池类型", "_"));//5
    _list.add(DeviceHardAndSoftInfo("电池容量", "_"));//6
    _list.add(DeviceHardAndSoftInfo("最大电量", "_"));//7
    _list.add(DeviceHardAndSoftInfo("当前电量", "_"));//8
    _list.add(DeviceHardAndSoftInfo("充电次数", "_"));//9
    _list.add(DeviceHardAndSoftInfo("手机厂商", "_"));//10
    CmdUtils.deviceModel((success, error, process, successListener) {
      if(success != "DONE"){
        debugPrint("型号为：$success");
        setState(() {
          _list[0].name = success.replaceAll("\n", "");
        });
      }
    });
    CmdUtils.deviceAndroidRelease((success, error, process, successListener) {
      if(success != "DONE"){
        debugPrint("安卓系统版本：$success");
        setState(() {
          _list[1].name = success.replaceAll("\n", "");
        });
      }
    });
    CmdUtils.deviceAndroidRelease((success, error, process, successListener) {
      if(success != "DONE"){
        debugPrint("安卓系统版本：$success");
        setState(() {
          _list[1].name = success.replaceAll("\n", "");
        });
      }
    });
    CmdUtils.deviceAndroidRelease((success, error, process, successListener) {
      if(success != "DONE"){
        debugPrint("安卓系统版本：$success");
        setState(() {
          _list[1].name = success.replaceAll("\n", "");
        });
      }
    });
    CmdUtils.deviceAndroidSdkVersion((success, error, process, successListener) {
      if(success != "DONE"){
        debugPrint("安卓SDK版本：$success");
        setState(() {
          _list[2].name = success.replaceAll("\n", "");
        });
      }
    });
    CmdUtils.deviceCpuAbi((success, error, process, successListener) {
      if(success != "DONE"){
        debugPrint("CPU架构：$success");
        setState(() {
          _list[3].name = success.replaceAll("\n", "");
        });
      }
    });
    CmdUtils.prop("ro.product.brand",(success, error, process, successListener) {
      if(success != "DONE"){
        debugPrint("手机厂商：$success");
        setState(() {
          _list[10].name = success.replaceAll("\n", "");
        });
      }
    });
    CmdUtils.deviceBattery((success, error, process, successListener) {
      //debugPrint(success);
      List<String> batteryArray = success.trim().replaceAll(" ", "").split("\r\n");
      for(String item in batteryArray){
        if(!item.contains(":")){
          continue;
        }
        String key = item.split(":")[0].trim();
        String value = item.split(":")[1].trim();
        if(key.startsWith("technology")){
          debugPrint("电池类型：$success");
          setState(() {
            _list[5].name = value;
          });
        }else if(key.startsWith("temperature")){
          debugPrint("电池温度：$success");
          setState(() {
            _list[4].name = "${int.parse(value)/10}摄氏度";
          });
        }else if(key.startsWith("scale")){
          debugPrint("最大电量：$success");
          setState(() {
            _list[7].name = value;
          });
        }else if(key.startsWith("voltage")){
          debugPrint("电池容量：$success");
          setState(() {
            _list[6].name = value;
          });
        }else if(key.startsWith("level")){
          debugPrint("当前电量：$success");
          setState(() {
            _list[8].name = value;
          });
        }else if(key.startsWith("Chargecounter")){
          debugPrint("充电次数：$success");
          setState(() {
            _list[9].name = value;
          });
        }
      }
    });
  }

  @override
  void dispose() {
    _mounted = false;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (provider == null) {
      provider = Provider.of<AdbCurrentChangeProvider>(context);
      debugPrint("注册监听");
      provider?.addListener(() {
        init();
      });
    }
    return Container(
      height: MediaQuery.of(context).size.height,
      width: MediaQuery.of(context).size.width,
      alignment: Alignment.topCenter,
      child: Column(
        children: [
          Row(
            children: [
              Container(
                height: 250,
                width: 250,
                margin: const EdgeInsets.all(10),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(20),
                  child: Container(
                    color: Colors.blueGrey,
                    child: Image.file(
                      _cover,
                      height: 250,
                      width: 250,
                      repeat: ImageRepeat.repeatY,
                      alignment: Alignment.topCenter,
                    ),
                  ),
                ),
              ),
              Expanded(
                  flex: 1,
                  child: Container(
                      height: 250,
                      width: MediaQuery.of(context).size.width,
                      child: ListView.builder(
                        itemCount: _list.length,
                        itemBuilder: (context, index) {
                          return SizedBox(
                            child: Row(
                              children: [
                                Expanded(
                                    flex: 3,
                                    child: Row(
                                      children: [
                                        Expanded(
                                            child: Text(
                                          _list[index].key,
                                          style: const TextStyle(
                                              fontWeight: FontWeight.bold),
                                        )),
                                        const Expanded(child: Text(":"))
                                      ],
                                    )),
                                Expanded(
                                    flex: 17, child: Text(_list[index].name))
                              ],
                            ),
                          );
                        },
                      )))
            ],
          ),
          Expanded(
            flex: 1,
            child: Container(
              margin: EdgeInsets.all(10),
              alignment: Alignment.topCenter,
              child: Row(
                children: [
                  Expanded(
                      child: ListView.builder(
                    itemCount: _displayInfoList.length,
                    itemBuilder: (context, index) {
                      return SizedBox(
                        child: Row(
                          children: [
                            Expanded(
                                flex: 3,
                                child: Row(
                                  children: [
                                    Expanded(
                                        child: Text(
                                          _displayInfoList[index].key,
                                      style: const TextStyle(
                                          fontWeight: FontWeight.bold),
                                    )),
                                    const Expanded(child: Text(":"))
                                  ],
                                )),
                            Expanded(flex: 17, child: Text(_displayInfoList[index].name))
                          ],
                        ),
                      );
                    },
                  )),
                  Expanded(
                      child: ListView.builder(
                    itemCount: _otherInfoList.length,
                    itemBuilder: (context, index) {
                      return SizedBox(
                        child: Row(
                          children: [
                            Expanded(
                                flex: 3,
                                child: Row(
                                  children: [
                                    Expanded(
                                        child: Text(
                                          _otherInfoList[index].key,
                                      style: const TextStyle(
                                          fontWeight: FontWeight.bold),
                                    )),
                                    const Expanded(child: Text(":"))
                                  ],
                                )),
                            Expanded(flex: 17, child: Text(_otherInfoList[index].name))
                          ],
                        ),
                      );
                    },
                  ))
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }
}
